package com.taxi.driver.common.retrofit;

import android.text.TextUtils;

import com.qianxx.network.Interceptor.ReceivedInterceptor;
import com.qianxx.network.Interceptor.RequestInterceptor;
import com.qianxx.network.converter.FastJsonConverterFactory;
import com.qianxx.utils.SP;
import com.taxi.driver.BuildConfig;

import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.X509TrustManager;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;

/**
 * BaseApi baseApi = new RequestUtil(BaseApi.class, "http://www.baidu.com", sp).getService();
 * <p>
 * Created on 16/5/22 下午8:21.
 *
 * @author binwin20
 */
public class RetrofitUtil {

    private RetrofitUtil() {

    }

    /**
     * @param tClass retrofitAPI 类
     * @param host   服务器地址（必须以 / 结尾）
     * @param sp     SharePreference 用于保存token、header等
     * @return
     */
    public static <T> T getService(Class<T> tClass, String host, SP sp) {
        OkHttpClient.Builder builder = new OkHttpClient.Builder()
                .addInterceptor(new ReceivedInterceptor(sp))
                .addInterceptor(new RequestInterceptor(sp));


        if (BuildConfig.FLAVOR_project.equals("Q201705XuanXuan")) {
            HttpsUtil httpsUtil = HttpsUtil.getIntance();
            SSLSocketFactory sslSocketFactory = httpsUtil.setCertificates();

            if (sslSocketFactory != null) {
                builder.hostnameVerifier((hostname, session) -> hostname.equals(session.getPeerHost()))
                        .sslSocketFactory(sslSocketFactory, new X509TrustManager() {
                            @Override
                            public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {

                            }

                            @Override
                            public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {

                            }

                            @Override
                            public X509Certificate[] getAcceptedIssuers() {
                                return new X509Certificate[0];
                            }
                        });
            }

        }

        OkHttpClient okHttpClient = builder.build();

        if (TextUtils.isEmpty(host)) {
            host = "http://localhost/";
        }
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(host)
                .client(okHttpClient)
                .addConverterFactory(FastJsonConverterFactory.create())  // 添加 fastJson 解析器
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) // 添加 RxJava 适配器
                .build();
        return retrofit.create(tClass);
    }
}
